import 'dart:async';

import 'package:amap_plugin_example/map_view.dart';
import 'package:flutter/material.dart';
import 'package:amap_plugin/index.dart';

class HomePage extends StatefulWidget {
  @override
  _HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
    Location _location = Location();
  StreamSubscription<Location> _locationSubScription;
  AmapLocation _amapPlugin = AmapLocation();
  @override
  void initState() {
    _locationSubScription = _amapPlugin.onLocationChanged.listen((location) {
    
      if (!mounted) return;
      setState(() {
        _location = location;
      });
    });
    super.initState();
  }

  Future<void> startLocation() async {
    await _amapPlugin.startLocation;
  }

  Future<void> stopLocation() async {
    await _amapPlugin.stopLocation;
  }

  @override
  void dispose() {
    if (_locationSubScription != null) {
      _locationSubScription.cancel();
    }
    super.dispose();
  }

  Future<Location> getLocation() async {
    Location location;
    try {
      location = await _amapPlugin.getLocation;
      print(location);
    } catch(e) {
      location = null;
    }
    if (!mounted) return null;
    setState(() {
      _location = location;
    });
    return null;
  }

  @override
  Widget build(BuildContext context) {
    return new Scaffold(
        appBar: new AppBar(
          title: const Text('Plugin example app'),
        ),
        body: new Center(
          child: Column(
            children: <Widget>[
              new FlatButton(
                  onPressed: () {
                    Navigator.of(context)
                        .push(MaterialPageRoute(builder: (context) {
                      return MapView();
                    }));
                  },
                  child: Text("显示地图")),
              new FlatButton(onPressed: startLocation, child: Text("开始定位")),
              new FlatButton(onPressed: stopLocation, child: Text("停止定位")),
              new FlatButton(onPressed: getLocation, child: Text("获取定位")),
              new Text('Running on: lat: ${_location?.lat}\n'),
              new Text('Running on: lng: ${_location?.lng}\n'),
              new Text('Running on: province: ${_location?.province}\n'),
              new Text('Running on:city: ${_location?.city}\n'),
              new Text('Running on:district: ${_location?.district}\n'),
              new Text('Running on: address: ${_location?.address}\n'),
              new Text("errorCode:${_location?.errorCode}"),
              new Text("errorInfo:${_location?.errorInfo}")
            ],
          ),
        ),
      );
  }
}